#!/usr/bin/env python3
"""
Standalone entrypoint for running the FastAPI server via uvicorn.
This is used by PyInstaller to build a single-file binary.
"""
from __future__ import annotations

import os
import sys
from typing import Optional

try:
    # Load .env if present
    from dotenv import load_dotenv  # type: ignore
    load_dotenv()
except Exception:
    pass


def _to_int(value: Optional[str], default: int) -> int:
    try:
        return int(value) if value is not None else default
    except Exception:
        return default


def main() -> None:
    # Ensure local package imports work when frozen and unfrozen
    base_dir = os.path.dirname(os.path.abspath(__file__))
    if base_dir not in sys.path:
        sys.path.insert(0, base_dir)

    import uvicorn  # noqa: WPS433

    host = os.getenv("HOST", "0.0.0.0")
    port = _to_int(os.getenv("PORT") or os.getenv("BACKEND_PORT"), 8000)

    # Default URLs if not provided
    os.environ.setdefault(
        "REDIS_URL", os.getenv("REDIS_URL", "redis://localhost:6379"),
    )
    os.environ.setdefault(
        "DATABASE_URL",
        os.getenv(
            "DATABASE_URL",
            "postgresql+psycopg://ignite_user:ignite_password@localhost:5432/textlabel_db",
        ),
    )

    # Import FastAPI app
    # Using a string target ensures PyInstaller can resolve modules when bundled
    import app.main  # ensure package discovery
    uvicorn.run("app.main:app", host=host, port=port, log_level="info")


if __name__ == "__main__":
    main()
